/* 
https://ai.baidu.com/support/news?action=detail&id=2390
百度公有云服务免费测试额度调整
5月26日（含）前登录控制台，完成实名认证并成功调用该产品方向下任一接口，我们会为您保留该产品方向下所有接口原有免费测试额度。
注：调整后的免费测试额度，您需要登录控制台，在对应产品的概览页领取所需接口的免费测试额度。
*/

/* 
By ClanK
QQ 965387139
2021年5月26日
*/
function ScreenCapture(isHorizontal) {
    let AllowThreads = threads.start(function () {//自动点击允许
        function isAllow() {
            return textMatches(/(允许|立即开始|同意)/).findOnce();
        };
        for (let i = 60; i >= 0; i--) {
            try {
                let Allow = isAllow();
                if (Allow) {
                    Allow.click();
                };
            } catch (error) {
                console.error(error);
            };
            sleep(1000)
        };
    });
    if (!requestScreenCapture(isHorizontal)) {//请求权限
        console.error("请求失败");
        return false;
    } else {
        console.warn("请求成功");
        AllowThreads.interrupt();//关闭线程
        return true;
    };
}
function GetAccessToken(APIKey, SecretKey) {
    let res = http.post("https://aip.baidubce.com/oauth/2.0/token", {
        'Content-Type': 'text/html;charset=utf-8',
        'grant_type': 'client_credentials',
        'client_id': APIKey,
        'client_secret': SecretKey,
    }, {
        headers: {
            'Accept-Language': 'zh-cn,zh;q=0.5',
            'User-Agent': 'Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11',
        }
    });
    try {
        let AccessToken = res.body.json().access_token;
        if (AccessToken) {
            let BaiDu = storages.create("BaiDu");
            let Time = parseInt(Date.parse(new Date()) / 1000 + 20 * 24 * 60 * 60);//有效期
            BaiDu.put("AccessToken", String(AccessToken));// 保存名称
            BaiDu.put("UpDataTime", String(Time));// 保存名称
            return AccessToken;
        };
    } catch (error) {
        console.error("获取错误：", error);
    };
    return false;
};
function ImgToBase64(ImgX, ImgY, ImgW, ImgH) {
    let Img = captureScreen();
    if (ImgX != null && ImgY != null) {
        if (ImgW == null || ImgH == null) {
            ImgW = device.width - ImgX;
            ImgH = device.height - ImgY;
        };
        Img = images.clip(Img, ImgX, ImgY, ImgW, ImgH);
    };
    let ImgReduce = images.scale(Img, 0.5, 0.5);
    let ImgBase64 = images.toBase64(ImgReduce);
    if (Img != null && !Img.isRecycled()) {
        Img.recycle();
    };
    if (ImgReduce != null && !ImgReduce.isRecycled()) {
        ImgReduce.recycle();
    };
    return ImgBase64;
};
function BaiDuOCr(AccessToken, ImgBase64, Type) {
    // API文档：https://cloud.baidu.com/doc/OCR/s/zk3h7xz52
    let url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";
    switch (Type) {
        case 0:   // 通用文字识别（标准版）         50,000次/天
            url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic";
            break;
        case 1:   // 通用文字识别（标准含位置版）    500次/天
            url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate";
            break;
        case 2:   // 通用文字识别（高精度版）        500次/天
            url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";
            break;
        case 3:   // 通用文字识别（高精度含位置版）	  50次/天
            url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general";
            break;
    };
    let res = http.post(url, {
        'Content-Type': 'text/html;charset=utf-8',
        'access_token': AccessToken,
        'image': ImgBase64,
    }, {
        headers: {
            'Accept-Language': 'zh-cn,zh;q=0.5',
            'User-Agent': 'Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11',
            'Content-Type': 'application/x-www-form-urlencoded',
        }
    });
    try {
        let Result = res.body.json();
        if (Result.words_result_num != 0) {
            return Result.words_result;
        } else {
            console.error('没有识别出文字');
            return false;
        };
    } catch (error) {
        console.error("识别错误：", error);
    };
    return false;
};
function BaiDuFaseDetect(AccessToken, ImgBase64) {
    // API文档：https://cloud.baidu.com/doc/FACE/s/yk37c1u4t
    let res = http.post('https://aip.baidubce.com/rest/2.0/face/v3/detect', {
        'Content-Type': 'text/html;charset=utf-8',
        'access_token': AccessToken,
        'image': ImgBase64,
        'image_type': 'BASE64',
        'face_field': 'beauty,face_type',
    }, {
        headers: {
            'Accept-Language': 'zh-cn,zh;q=0.5',
            'User-Agent': 'Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11',
            'Content-Type': 'application/json',
        }
    });
    try {
        let Result = res.body.json();
        if (Result.error_code != 0) {
            console.error(Result.error_code, Result.error_msg);
            console.error('人脸识别失败');
            return Result.error_code;
        } else {
            console.log(Result.result.face_list[0].beauty, '分');
            return Result.result.face_list;
        };
    } catch (error) {
        console.error("识别错误：", error);
    };
    return false;
};
function BaiDuBodyAnalysis(AccessToken, ImgBase64) {
    // API文档：https://cloud.baidu.com/doc/BODY/s/0k3cpyxme
    let res = http.post('https://aip.baidubce.com/rest/2.0/image-classify/v1/body_analysis', {
        'Content-Type': 'text/html;charset=utf-8',
        'access_token': AccessToken,
        'image': ImgBase64,
    }, {
        headers: {
            'Accept-Language': 'zh-cn,zh;q=0.5',
            'User-Agent': 'Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11',
            'Content-Type': 'application/x-www-form-urlencoded',
        }
    });
    try {
        let Result = res.body.json();
        if (Result.person_num == 0) {
            console.error(Result);
            console.error('人体关键点识别失败');
            return Result.error_code;
        } else {
            console.info('人体数量：', Result.person_num);
            return Result.person_info;
        };
    } catch (error) {
        console.error("识别错误：", error);
    };
    return false;
};
function BaiDuTextCensor(AccessToken, text) {
    // API文档：https://cloud.baidu.com/doc/ANTIPORN/s/Rk3h6xb3i
    let res = http.post('https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined', {
        'Content-Type': 'text/html;charset=utf-8',
        'access_token': AccessToken,
        'text': text,
    }, {
        headers: {
            'Accept-Language': 'zh-cn,zh;q=0.5',
            'User-Agent': 'Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11',
            'Content-Type': 'application/x-www-form-urlencoded',
        }
    });
    try {
        let Result = res.body.json();
        if (Result.conclusion == '合规') {
            return true;
        } else {
            for (let i = 0; i < Result.data.length; i++) {
                console.log(Result.data[i].msg);
            };
            return false;
        };
    } catch (error) {
        console.error("识别错误：", error);
    };
    return false;
};
function BaiDuImageRecognition(AccessToken, ImgBase64) {
    // API文档：https://cloud.baidu.com/doc/IMAGERECOGNITION/s/Xk3bcxdum
    let res = http.post('https://aip.baidubce.com/rest/2.0/image-classify/v1/object_detect', {
        'Content-Type': 'text/html;charset=utf-8',
        'access_token': AccessToken,
        'image': ImgBase64,
    }, {
        headers: {
            'Accept-Language': 'zh-cn,zh;q=0.5',
            'User-Agent': 'Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11',
            'Content-Type': 'application/x-www-form-urlencoded',
        }
    });
    try {
        let Result = res.body.json();
        if (Result.result) {
            return Result.result;
        } else {
            console.info('图像单主体检测失败：', Result.error_code, Result.error_msg);
            return Result.person_info;
        };
    } catch (error) {
        console.error("识别错误：", error);
    };
    return false;
};
function BaiDuRealtimeSearch(AccessToken, ImgBase64, Type, Brief) {
    // API文档：https://cloud.baidu.com/doc/IMAGESEARCH/s/3k3bczqz8
    let url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/similar/add';
    switch (Type) {
        case 0:   // 入库
            url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/similar/add';
            break;
        case 1:   // 搜索
            url = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/similar/search';
            break;
    };
    if (!Brief) {
        Brief = 'Brief';
    };
    let res = http.post(url, {
        'Content-Type': 'text/html;charset=utf-8',
        'access_token': AccessToken,
        'image': ImgBase64,
        'brief': Brief,
    }, {
        headers: {
            'Accept-Language': 'zh-cn,zh;q=0.5',
            'User-Agent': 'Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11',
            'Content-Type': 'application/x-www-form-urlencoded',
        }
    });
    try {
        let Result = res.body.json();
        switch (Type) {
            case 0:   // 入库
                if (Result.error_code) {
                    console.log('图片入库：', Result.error_code, Result.error_msg);
                    return Result.result;
                } else {
                    return Result.cont_sign;
                };
            case 1:   // 搜索
                if (!Result.result) {
                    console.log('图片搜索：', Result.has_more, Result.result_num);
                    return false;
                } else {
                    return Result.result;
                };
        };
    } catch (error) {
        console.error("识别错误：", error);
    };
    return false;
};
function BaiDuSelfieAnime(AccessToken, ImgBase64) {
    // API文档：https://cloud.baidu.com/doc/IMAGEPROCESS/s/Mk4i6olx5
    let res = http.post('https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime', {
        'Content-Type': 'text/html;charset=utf-8',
        'access_token': AccessToken,
        'image': ImgBase64,
    }, {
        headers: {
            'Accept-Language': 'zh-cn,zh;q=0.5',
            'User-Agent': 'Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11',
            'Content-Type': 'application/x-www-form-urlencode',
        }
    });
    try {
        let Result = res.body.json();
        if (!Result.image) {
            console.error('人物动漫化失败');
            return false;
        } else {
            return Result.image;
        };
    } catch (error) {
        console.error("识别错误：", error);
    };
    return false;
};

let APIKey = '';
let SecretKey = '';
let BaiDu = storages.create("BaiDu");
let AccessToken = BaiDu.get("AccessToken", '');                     // 存储AccessToken
let UpDataTime = BaiDu.get("UpDataTime", 0);                        // AccessToken有效期
if (!AccessToken || Number(UpDataTime) < parseInt(Date.parse(new Date()) / 1000)) {
    AccessToken = GetAccessToken(APIKey, SecretKey);                // 重新获取AccessToken
};
console.log(AccessToken);
ScreenCapture();                                                     // 申请截图权限
let ImgBase64 = ImgToBase64();                                       // 截图并转Base64

let Words = BaiDuOCr(AccessToken, ImgBase64);                        // 通用识别文字
if (Words) {
    console.info("通用识别文字:", Words);
};
let Fase = BaiDuFaseDetect(AccessToken, ImgBase64);                  // 人脸识别
if (Fase) {
    console.info("人脸识别:", Fase);
};
let Body = BaiDuBodyAnalysis(AccessToken, ImgBase64);                // 人体关键点识别
if (Body) {
    console.info("人体关键点识别:", Fase);
};
let text = '祝你全家花开富贵'
let TextCensor = BaiDuTextCensor(AccessToken, text);                 // 文字内容审核
if (TextCensor) {
    console.info('文字合规');
} else {
    console.info('文字不合规');
};
let Recognition = BaiDuImageRecognition(AccessToken, ImgBase64);     // 图像识别
if (Recognition) {
    console.info("图像识别:", Recognition);
};
let ImgAdd = BaiDuRealtimeSearch(AccessToken, ImgBase64, 0, '测试'); // 图像入库
if (ImgAdd) {
    console.info("图像入库:", ImgAdd);
};
let ImgSearch = BaiDuRealtimeSearch(AccessToken, ImgBase64, 1);      // 图像搜索
if (ImgSearch) {
    console.info("图像搜索:", ImgSearch);
};

let SelfieAnime = BaiDuSelfieAnime(AccessToken, ImgBase64);          // 人物动漫化
if (SelfieAnime) {
    let SelfieAnimeImg = images.fromBase64(SelfieAnime);
    if (SelfieAnimeImg) {
        images.save(SelfieAnimeImg, "/sdcard/1.jpg", "jpg", 50);
        if (SelfieAnimeImg != null && !SelfieAnimeImg.isRecycled()) {
            SelfieAnimeImg.recycle();
        };
        app.viewFile("/sdcard/1.jpg");
    };
};
